package net.roobook.server.system.configure;

import net.roobook.common.handler.RoobookAccessDeniedHandler;
import net.roobook.common.handler.RoobookAuthExceptionEntryPoint;
import net.roobook.server.system.properties.RoobookServerSystemProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

/**
 * @Author Roobook
 * @description 系统资源服务器配置类
 * @date 2022/4/8
 */
@Configuration
@EnableResourceServer
public class RoobookServerSystemResourceServerConfigure  extends ResourceServerConfigurerAdapter {

    @Autowired
    private RoobookAccessDeniedHandler accessDeniedHandler;
    @Autowired
    private RoobookAuthExceptionEntryPoint exceptionEntryPoint;
    @Autowired
    private RoobookServerSystemProperties properties;
    @Override
    public void configure(HttpSecurity http) throws Exception {
        String[] anonUrls = StringUtils.splitByWholeSeparatorPreserveAllTokens(properties.getAnonUrl(), ",");

        http.csrf().disable()
                .requestMatchers().antMatchers("/**")
                .and()
                .authorizeRequests()
                .antMatchers(anonUrls).permitAll()
                .and()
                .authorizeRequests().antMatchers("/actuator/**").permitAll()
                .antMatchers("/**").authenticated();
    }


    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.authenticationEntryPoint(exceptionEntryPoint)
                .accessDeniedHandler(accessDeniedHandler);
    }
}
